#!/bin/bash
cd "$(dirname "$0")"
if [ -h "$0" ];then
	cd "$(dirname "$(readlink "$0")")"
fi
conf(){
	if [ ! -n "$2" ];then
		return 1
	fi
	if [ "$1" == "-l" ];then
		echo "$2" | sed -n 'p;n'
	elif [ "$1" == "-r" ];then
		if [ ! -n "$3" ];then
			return 1
		fi
		line="$(echo "$2" | sed -n 'p;n' | grep -Fxn "$3" | sed -n '1p' | cut -d ':' -f 1)"
		if [ -n "$line" ];then
			echo "$2" | sed -n "$[$line*2]p" | sed 's/\\n/\'$'\n''/g' | sed 's/\\ /\\/g'
		else
			return 1
		fi
	elif [ "$1" == "-m" ];then
		if [ ! -n "$4" ];then
			return 1
		fi
		line="$(echo "$2" | sed -n 'p;n' | grep -Fxn "$3" | sed -n '1p' | cut -d ':' -f 1)"
		if [ -n "$line" ];then
			line="$[$line*2]"
			echo -n "$(echo "$2" | sed -n "1,$[$line-1]p")"$'\n'"$(echo "$4"$'\n' | sed 's/\\/\\ /g' | sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/\\n/g' | sed '$s/..$//')"$'\n'"$(echo "$2" | sed -n "$[$line+1],$(echo "$2" | wc -l)p")"
		else
			return 1
		fi
	else
		return 1
	fi
}
gettrans(){
	if [ ! -n "$1" ];then
		return 1
	fi
	trans="$(conf -r "$lang" "$1")"
	if [ -n "$trans" ];then
		echo "$trans"
	else
		echo "[translation for $1 not found]"
	fi
}
genmenu(){
	if [ ! -n "$1" ];then
		return 1
	fi
	menu=()
	cnt=0
	title="$1"
	shift
	for loop in "$@"
	do
		menu[$cnt]=$[$cnt/2+1]
		menu[$[$cnt+1]]="$loop"
		let cnt=cnt+2
	done
	dialogret --menu "$title" 0 0 0 "${menu[@]}"
}
judge(){
	if [ ! -n "$3" ];then
		return 1
	fi
	if [ -n "$(eval "$1||echo")" ];then
		echo "$3"
	else
		echo "$2"
	fi
}
dialogret(){
	tmp="$(mktemp)"
	dialog "$@" 1>&2 2>"$tmp"
	cat "$tmp"
	rm "$tmp"
}
argeval(){
	if [ ! -n "$1" ];then
		return 1
	fi
	echo 'echo "$'"$1"'"'
}
menu(){
	tit="$1"
	item=()
	cnt=1
	shift
	for loop in "$@"
	do
		item[$[$cnt-1]]="`gettrans "$(eval "$(argeval "$cnt")")"`"
		let cnt=cnt+1
	done
	eval "$(argeval "$(genmenu "$tit" "${item[@]}")")"
}
lang="$(cat "setting/language/$(conf -r "$(cat "setting/config/config.tcfg")" language)".tlng)"
if [ ! -f "setting/config/config.tcfg" ];then
	dialog --title 'Oops!' --msgbox "It seems that you haven't installed correctly. Try reinstall the program." 0 0
	exit 1
fi
while true
do
	ch="$(menu "TUIDE - main menu" create_project edit_file compile run compile_run setting exit)"
	case "$ch" in
		"exit")
			if dialog --title "`gettrans confirm`" --yesno "`gettrans confirm_exit`" 0 0;then
				exit
			fi
			;;
	esac
done
